package centerberg.game;

import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics2D;

/**
 * A simple button in a menu visually represented by text. Changes color when
 * the button is selected.
 * 
 * @author Andreas Svanberg
 */
public class Button
{
    private Action action;
    private String text;
    
    /**
     * Creates a new button with the given text.
     * 
     * @param text text to display on the button
     */
    public Button(String text)
    {
        this.text = text;
    }
    
    /**
     * Sets the action to perform when the button is pressed.
     * 
     * @param action action to execute
     */
    public void setAction(Action action)
    {
        this.action = action;
    }
    
    /**
     * Presses this button, executing its associated action if there is one.
     */
    public void pressed()
    {
        if (action != null)
            action.execute();
    }
    
    /**
     * Draws the button.
     * 
     * @param g graphics object to draw on
     * @param y y-coordinate of the top most button
     * @param selected the selected state of the button
     */
    public void draw(Graphics2D g, int y, boolean selected)
    {
        g.setColor(selected ? Color.GREEN : Color.WHITE);
        
        FontMetrics fm = g.getFontMetrics();
        
        int width = fm.stringWidth(text);
        int x = (Menu.MENU_WIDTH - width) / 2;
        
        g.drawString(text, x, y);
    }
}